/**
 * @license
 * Copyright Alibaba.com All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */

import { ApesTreeNode } from './apes-tree-base-node';
import { ApesTreeBaseService } from './apes-tree-base.service';

export class ApesTreeBase {
  constructor(public apesTreeService: ApesTreeBaseService) {}

  /**
   * Coerces a value({@link any[]}) to a TreeNodes({@link ApesTreeNode[]})
   */
  coerceTreeNodes(
    // tslint:disable-next-line:no-any
    value: any[]
  ): ApesTreeNode[] {
    let nodes: ApesTreeNode[] = [];
    if (!this.apesTreeService.isArrayOfApesTreeNode(value)) {
      // has not been new ApesTreeNode
      nodes = value.map(item => new ApesTreeNode(item, null, this.apesTreeService));
    } else {
      nodes = value.map((item: ApesTreeNode) => {
        item.service = this.apesTreeService;
        return item;
      });
    }
    return nodes;
  }

  /**
   * Get all nodes({@link ApesTreeNode})
   */
  getTreeNodes(): ApesTreeNode[] {
    return this.apesTreeService.rootNodes;
  }

  /**
   * Get {@link ApesTreeNode} with key
   */
  getTreeNodeByKey(key: string): ApesTreeNode | null {
    // flat tree nodes
    const nodes: ApesTreeNode[] = [];
    const getNode = (node: ApesTreeNode): void => {
      nodes.push(node);
      node.getChildren().forEach(n => {
        getNode(n);
      });
    };
    this.getTreeNodes().forEach(n => {
      getNode(n);
    });
    return nodes.find(n => n.key === key) || null;
  }

  /**
   * Get checked nodes(merged)
   */
  getCheckedNodeList(): ApesTreeNode[] {
    return this.apesTreeService.getCheckedNodeList();
  }

  /**
   * Get selected nodes
   */
  getSelectedNodeList(): ApesTreeNode[] {
    return this.apesTreeService.getSelectedNodeList();
  }

  /**
   * Get half checked nodes
   */
  getHalfCheckedNodeList(): ApesTreeNode[] {
    return this.apesTreeService.getHalfCheckedNodeList();
  }

  /**
   * Get expanded nodes
   */
  getExpandedNodeList(): ApesTreeNode[] {
    return this.apesTreeService.getExpandedNodeList();
  }

  /**
   * Get matched nodes(if nzSearchValue is not null)
   */
  getMatchedNodeList(): ApesTreeNode[] {
    return this.apesTreeService.getMatchedNodeList();
  }
}
